<template>
  <section>
    <div class="container">
      <div class="filter-container">
        <!-- <common-input @keyup.enter.native="handleFilter" class="w200" placeholder="专场关键字" v-model="keyword" /> -->

        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="合伙人id"
          v-model="listQuery.partnerId" />
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="小店id"
          v-model="listQuery.sellerId" />
        <common-input @keyup.enter.native="handleFilter" class="w200 ml10" placeholder="关键字"
          v-model="listQuery.keyword" />
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button @click="addAccount" type="primary" size="mini" class="btn">新增账号</el-button>
        <!-- <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button> -->

      </div>

      <el-table :data="tableData" style="width:100%" max-height="720" class="shop_table_list" :cell-style="tc"
        :header-cell-style="tccolor">
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="type" label="类型">
          <template slot-scope="scope">
            {{ scope.row.type === 1 ? "平台用户" : scope.row.type === 2 ? "合伙人用户" : '小店用户' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ scope.row.status === 1 ? "正常" : "禁用" }}
            <!-- <el-switch @change="switchStatus($event, scope.row.id)" v-model="scope.row.status" active-color="#cccccc"
              inactive-color="#13ce66" active-value="0" inactive-value="1">
            </el-switch> -->
          </template>
        </el-table-column>
        <el-table-column prop="loginTime" label="最近登录时间"></el-table-column>
        <el-table-column prop="time" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editDialog(scope.row.id)"
              style="margin-right:10px">修改用户</el-button>
            <el-button type="primary" size="mini" @click="openDialog(scope.row)"
              style="margin-right:10px">修改密码</el-button>
            <!-- <el-button type="primary" size="mini" @click="resetPassword(scope.row.id)">重置密码</el-button> -->
            <el-popconfirm title="确认要将密码重置为123456 ?" @confirm="resetPassword(scope.row.id)">
              <el-button slot="reference" type="primary" size="mini">重置密码</el-button>
            </el-popconfirm>
            <el-popconfirm title="是否要删除此账号 ?" @confirm="deleteadmin(scope.row.id)">
              <el-button slot="reference" type="primary" size="mini">删除用户</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-col :span="24">
        <div class="pagination">
          <el-pagination background @current-change="handleCurrentChange" :current-page="listQuery.pageNum"
            :page-size="listQuery.pageSize" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>
      </el-col>
      <el-dialog title="修改密码" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false" @closed="cancel">
        <el-form :model="formData" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input v-model="formData.oldPassword" placeholder="请输入旧密码" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="password">
            <el-input v-model="formData.password" placeholder="请输入新密码" type="password"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input v-model="formData.confirmPassword" placeholder="确认新密码" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">修改密码</el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisibleAdd" width="60%" :close-on-click-modal="false"
        @closed="cancel">
        <el-form :model="formDataAdd" :rules="rulesAdd" ref="formAdd" label-width="100px" class="formAdd">
          <el-form-item label="用户名" prop="username" class="formItem">
            <el-input v-model="formDataAdd.username" placeholder="请输入用户名" type="text"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" class="formItem">
            <el-input v-model="formDataAdd.password" placeholder="请输入密码" type="password"></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="icon" class="formItem">
            <!-- <el-input v-model="formDataAdd.icon" placeholder="头像" type="password"></el-input> -->
            <pic-sel style="float:left" v-model="formDataAdd.icon" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email" class="formItem">
            <el-input v-model="formDataAdd.email" placeholder="请输入邮箱" type="text"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile" class="formItem">
            <el-input v-model="formDataAdd.mobile" placeholder="请输入手机号" type="text"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickName" class="formItem">
            <el-input v-model="formDataAdd.nickName" placeholder="请输入昵称" type="text"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="roleIds" class="formItem">
            <el-select v-model="formDataAdd.roleIds" multiple placeholder="请选择" @change="changeRole">
              <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="note" class="formItem">
            <el-input v-model="formDataAdd.note" placeholder="请输入备注信息" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type" class="formItem">
            <el-select class="w200 ml10" v-model="formDataAdd.type" placeholder="选择管理员类型" @change="changeType"
              clearable>
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="账号状态" prop="status" class="formItem">

            <el-radio-group v-model="formDataAdd.status">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="合伙人ID" prop="partnerId">
            <el-input v-model="formDataAdd.partnerId" placeholder="请输入合作人ID" type="text"></el-input>
          </el-form-item>
          <el-form-item label="小店ID" prop="sellerId">
            <el-input v-model="formDataAdd.sellerId" placeholder="请输入小店ID" type="text"></el-input>
          </el-form-item> -->
          <el-form-item label="服务经理" prop="serviceManager" class="formItem">

            <el-radio-group v-model="formDataAdd.serviceManager">
              <el-radio :label="0">不是</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="绑定会员id" prop="memberId" class="formItem" v-if="formDataAdd.serviceManager">
            <el-select v-model="formDataAdd.memberId" filterable remote reserve-keyword placeholder="请输入绑定会员id"
              :remote-method="getMemberList" :loading="loading">
              <el-option v-for="item in memberIdList" :key="item.id" :label="item.id" :value="item.id">
              </el-option>
            </el-select>
            <!-- <el-input v-model="formDataAdd.memberId" placeholder="请输入绑定会员id" type="text"></el-input> -->
          </el-form-item>



          <el-form-item style="display: flex; justify-content: flex-end; width: 100%">
            <el-button type="primary" @click="submitAdd">确定</el-button>
            <el-button @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </div>
  </section>
</template>

<script>
import {
  adminList,
  adminInfo,
  adminUpdate,
  adminAdd,
  updatePassword,
  updateMyPassword,
  adminDelete,
  updateStatus,
  roleUpdate,
  roleListAll,
  getRole,
  adminRoleUpdate
} from '@/api/admin'
import {
  member_list
} from '@/api/member'
export default {
  components: {
    'pic-sel': () => import('../../components/PicSel/index')
  },
  data() {
    return {
      tableData: [],
      form: {
        page: 1
      },
      dialogTitle: '新增',
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        partnerId: undefined,
        sellerId: 0,
      },
      loading: false,
      keyword: '',
      total: 0,
      dialogVisible: false,
      dialogVisibleAdd: false,
      dialogVisibleRole: false,
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 8, message: '密码至少为8个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: this.checkConfirmPassword, trigger: 'blur' }
        ]
      },
      rulesAdd: {
        username: [
          { required: true, message: '用户名必填', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '类型必需选择', trigger: 'blur' },
        ],
        roleIds: [
          { required: true, message: '角色必需选择', trigger: 'blur' },
        ],
      },
      typeList: [
        { id: 1, name: '平台用户' },
        { id: 2, name: '合伙人用户' },
        { id: 3, name: '小店用户' }
      ],
      formData: {
        id: 0,
        username: '',
        oldPassword: '',
        password: '',
        confirmPassword: ''
      },
      formRole: {
        adminId: 0,
        roleIds: []
      },
      formDataAdd: {
        id: '',
        username: '',
        password: '',
        icon: '',
        email: '',
        nickName: '',
        note: '',
        status: 1,
        type: '',   //类型，1：平台用户，2：合伙人用户，3小店用户
        typeText: '',
        partnerId: '',
        sellerId: '',
        createBy: '',
        updateBy: '',
        serviceManager: 0,
        memberId: '',
        mobile: '',
        roleIds: [],
        roleIdsText: ''
      },
      roleList: [],
      role: '',
      memberIdList: [],
    }
  },
  mounted() {

    this.getAdminList()
  },
  methods: {
    // 远程搜索
    remoteMethod() { },
    changeType(e) {
      console.log(e, this.typeList.find(item => item.id == e).name)
      this.formDataAdd.type = e
      this.formDataAdd.typeText = this.typeList.find(item => item.id == e).name
    },
    // 搜索
    handleFilter() {
      this.listQuery.pageNum = 1;
      this.getAdminList();
    },
    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
    handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getAdminList();
            },
    // 取消
    cancel() {
      this.dialogVisible = false
      // this.$refs['form'].clearValidate()
      this.formData = {
        id: 0,
        username: '',
        oldPassword: '',
        password: '',
        confirmPassword: ''
      }
    },



    // 获取角色列表
    getRoleList() {
      roleListAll().then(res => {
        if (res.code === 200) {
          // res.data.data.forEach(item => {
          //   item.last_time_text = item.last_time || '无'
          // })
          console.log(res)
          this.roleList = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 修改信息弹窗
    editDialog(id) {
      
      this.dialogTitle = "修改"
      let sid = id
      this.getRoleList()
      // this.getRole(id)
      if (id) {
        adminInfo(sid).then(res => {
          console.log(res)
          if (res.code === 200) {
            // this.$message.success('修改成功')
            this.formDataAdd = res.data

            this.formDataAdd.type === 1 ? this.formDataAdd.typeText = "平台用户" : this.formDataAdd.type === 2 ? this.formDataAdd.typeText = "合伙人用户" : this.formDataAdd.typeText = '小店用户'

            this.dialogVisibleAdd = true
            this.formDataAdd.password = ''
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },


    // 修改密码
    submit() {

      this.$refs['form'].validate(valid => {
        if (valid) {
          updatePassword(this.formData).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message.success('修改成功')
              this.formData = {
                id: 0,
                username: '',
                oldPassword: '',
                password: '',
                confirmPassword: ''
              }
              this.dialogVisible = false
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    // 新增
    submitAdd() {
      this.$refs['formAdd'].validate(valid => {
        if (valid) {
          if (this.formDataAdd.serviceManager) {

            this.formDataAdd.memberId ? '' : this.$message.error('请输入绑定会员id')
            return false
          }
          if (this.formDataAdd.id) {
            adminUpdate(this.formDataAdd).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('修改成功')

                this.dialogVisibleAdd = false
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            if (this.formDataAdd.password.length < 8) {
              this.$message.error('密码至少为8个字符')
              return false
            }
            adminAdd(this.formDataAdd).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('创建成功')
                this.getAdminList()
                this.dialogVisibleAdd = false
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    // 删除
    deleteadmin(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminDelete(id).then(res => {
          if (res.code === 200) {
            this.getAdminList()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      }).catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel'
                ? '已经取消删除'
                : '停留在当前页面'
            })
          });

    },
    // 检测两次密码是否一致
    checkConfirmPassword(rule, value, callback) {
      if (value !== this.formData.new_password) {
        return callback(new Error('两次输入的密码不一致'))
      } else {
        return callback()
      }
    },
    // 修改状态
    switchStatus(e, id) {

      let data = {
        status: Number(e)
      }

      console.log(e, id, data)
      updateStatus(data, id).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getRoleList()
        } else {
          this.$message.error(res.message)
        }
      })


    },
    changeRole(e) {
      console.log(e, this.formDataAdd.roleIds)

    },
    // 获取列表
    getAdminList() {
      console.log("会员列表")
      adminList(this.listQuery).then(res => {
        if (res.code === 200) {
          console.log("会员列表", res)
          this.tableData = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 修改密码按钮
    openDialog(row) {

      this.dialogVisible = true
      this.formData.id = row.id
      this.formData.username = row.username
    },
    // 分页
    pageChange(page) {
      this.form.page = page
      this.getAdminList()
    },
    // 搜索指定会员id
    getMemberList(e) {
      console.log(e)
      if (e) {
        let data = {
          keyword: e
        }
        member_list(data).then(res => {
          console.log(res)
          this.memberIdList = res.data.list
        })
      }

    },
    // 新增按钮
    addAccount() {
      this.getRoleList()
      this.formDataAdd = {
        id: '',
        username: '',
        password: '',
        icon: '',
        email: '',
        nickName: '',
        note: '',
        status: 1,
        type: '',
        partnerId: '',
        sellerId: '',
        createBy: '',
        updateBy: '',
        serviceManager: 0,
        memberId: '',
        mobile: ''
      }
      this.dialogTitle = '新增管理员'
      this.dialogVisibleAdd = true
    },
    // 重置密码
    resetPassword(id) {
      let data = {
        id: id,
        password: '123456'
      }


      updatePassword(data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('重置成功')

        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="scss" scpoed>
.container {

  // width:100% !important;
  // padding: 20px !important;
  .btn {
    margin-bottom: 20px;

    .btn-box {
      display: flex;
    }
  }

  .pagination {
    margin-top: 20px;
    float: right;
  }
}

.formAdd {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .formItem {
    width: 50%;
  }
}
</style>
